package org.jacp.demo.ui.handler;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

import org.jacp.demo.util.DropShadowPanel;

/**
 * @author Patrick Symmangk
 * 
 * 
 */
public class ImageTransferHandler extends TransferHandler implements
	Transferable {

    /**
	 * 
	 */
    private static final long serialVersionUID = -2613648152819488879L;

    private static final DataFlavor flavors[] = { DataFlavor.stringFlavor };

    private String filePath = "";

    @Override
    public int getSourceActions(final JComponent c) {
	return TransferHandler.COPY;
    }

    @Override
    public boolean canImport(final JComponent comp, final DataFlavor flavor[]) {
	if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
	    return false;
	}
	for (final DataFlavor element : flavor) {
	    for (final DataFlavor flavor2 : flavors) {
		if (element.equals(flavor2)) {
		    return true;
		}
	    }
	}
	return false;
    }

    @Override
    public Transferable createTransferable(final JComponent comp) {
	// Clear
	if (comp instanceof DropShadowPanel) {
	    final DropShadowPanel panel = (DropShadowPanel) comp;
	    filePath = panel.getFilePath();
	    return this;
	}
	return null;
    }

    @Override
    public boolean importData(final JComponent comp, final Transferable t) {

	if (comp instanceof JLabel) {
	    final JLabel label = (JLabel) comp;
	    if (t.isDataFlavorSupported(flavors[0])) {
		try {
		    final String s = t.getTransferData(flavors[0]).toString();
		    label.setText(s);
		    return true;
		} catch (final UnsupportedFlavorException ignored) {
		} catch (final IOException ignored) {
		}
	    }
	}
	return false;
    }

    // Transferable
    @Override
    public Object getTransferData(final DataFlavor flavor) {
	if (isDataFlavorSupported(flavor)) {
	    return filePath;
	}
	return null;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
	return flavors;
    }

    @Override
    public boolean isDataFlavorSupported(final DataFlavor flavor) {
	return flavors[0].equals(flavor);
    }
}